package middleware

import (
	"github.com/gin-gonic/gin"
	v1 "golang-sgg-daijia/api/v1"
	"golang-sgg-daijia/internal/const/redisconst"
	"golang-sgg-daijia/internal/repository/redis"
	"golang-sgg-daijia/pkg/log"
	"net/http"
	"strconv"
)

func UserLoginAuth(logger *log.Logger, rdb redis.RedisClient) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.Request.Header.Get("token")
		if token == "" {
			v1.HandleError(ctx, http.StatusUnauthorized, v1.ErrUnauthorized, nil)
			ctx.Abort()
			return
		}
		// 根据token查redis中对应的用户id
		IDStr, err := rdb.Get(ctx, redisconst.UserLoginKeyPrefix+token)
		if err != nil {
			v1.HandleError(ctx, http.StatusInternalServerError, v1.ErrInternalServerError, nil)
			ctx.Abort()
			return
		}
		ID, err := strconv.ParseInt(IDStr, 10, 64)
		if err != nil {
			v1.HandleError(ctx, http.StatusUnauthorized, v1.ErrUnauthorized, nil)
			ctx.Abort()
			return
		}
		ctx.Set("ID", ID)
		ctx.Next()
	}
}
